package com.kayden.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kayden.blog.common.exception.BlogException;
import com.kayden.blog.common.pojo.dataobject.BlogInfo;
import com.kayden.blog.common.pojo.dataobject.UserInfo;
import com.kayden.blog.common.pojo.request.UserLoginRequest;
import com.kayden.blog.common.pojo.response.UserInfoResponse;
import com.kayden.blog.common.pojo.response.UserLoginResponse;
import com.kayden.blog.common.utils.BeanTransUtils;
import com.kayden.blog.common.utils.JwtUtils;
import com.kayden.blog.common.utils.SecurityUtil;
import com.kayden.blog.mapper.UserInfoMapper;
import com.kayden.blog.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Resource(name = "blogServiceImpl")
    private BlogServiceImpl blogServiceImpl;

    @Override
    public UserLoginResponse checkPassword(UserLoginRequest userLoginRequest) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserInfo::getUserName, userLoginRequest.getUsername()).eq(UserInfo::getDeleteFlag,0);
        //TODO add try catch
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);
        if (userInfo == null) {
            throw new BlogException("用户不存在");
        }
        if (!SecurityUtil.verify(userLoginRequest.getPassword(), userInfo.getPassword())){
            throw new BlogException("用户密码错误");
        }
        Map<String,Object> map = new HashMap<>();
        map.put("id",userInfo.getId());
        map.put("name",userInfo.getUserName());
        String token = JwtUtils.getToken(map);
        return new UserLoginResponse(userInfo.getId(),token);
    }

    @Override
    public UserInfoResponse getUserInfo(Integer userId) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserInfo::getDeleteFlag,0).eq(UserInfo::getId,userId);
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);
        return BeanTransUtils.trans(userInfo);
    }

    @Override
    public UserInfoResponse getAuthorInfo(Integer blogId) {
        BlogInfo blogInfo = blogServiceImpl.getBlogInfo(blogId);
        if(blogInfo == null || blogInfo.getUserId()<=0){
            throw new BlogException("博客不存在");
        }
        return getUserInfo(blogInfo.getUserId());
    }
}
